"use strict";

import Vue from 'vue'
import axios from 'axios'
import { Loading, Message } from 'element-ui';

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
	baseURL: 'http://127.0.0.1:8090'
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
    return response;
  },
  function(error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

Plugin.install = function(Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;

export const lxlaxios = _axios
export const request = (url,method,params,callback) => {
// 加载组件
const lxlLoading = Loading.service({
	text: '加载中......'
})
const lxlconfig = {
	method: method,
}
if (method === 'get') {
	lxlconfig.params = params
}else{
	const formData = new FormData()
	for (const key in params) {
		if (params[key] instanceof Array) {
			for (let i = 0; i < params[key].length; i++) {
				formData.append(key,params[key][i])
			}
		} else {
			formData.append(key,params[key])
		}
	}
	lxlconfig.data = formData
}
_axios.request(url,lxlconfig
	).then(response => {
	if (response.data.code === 200){
		if (response.data.message){
			Message.success(response.data.message)
		}
		callback(response.data.content);
	} else {
		Message.error(response.data.message)
	}
	}).catch(error => {
		Message.error(error.message)
	}).finally(() => {
		lxlLoading.close()
	})
}

export const get = (url,params,callback) => {
	request(url, 'get', params, callback)
}

export const post = (url,params,callback) => {
	request(url, 'post', params, callback)
}